<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div class="search" v-show="showSearch">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                                <el-form-item label="订单编码" prop="orderCode">
                                    <el-input v-model="queryParams.orderCode" placeholder="请输入订单编码" clearable style="width: 240px" @keyup.enter="handleQuery"/>
                                </el-form-item>
                                <el-form-item label="订单总额" prop="money">
                                    <el-input v-model="queryParams.money" placeholder="请输入订单总额" clearable style="width: 240px" @keyup.enter="handleQuery"/>
                                </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </transition>

        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['demo:orderMain:add']">新增 </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['demo:orderMain:edit']">修改</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['demo:orderMain:remove']">删除</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['demo:orderMain:export']">导出</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </template>

            <el-table v-loading="loading" :data="orderMainList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center"/>
                        <el-table-column label="主键" align="center" prop="id" v-if="true"/>
                        <el-table-column label="订单编码" align="center" prop="orderCode"/>
                        <el-table-column label="客户编号" align="center" prop="customerId">
                            <template #default="scope">

                            </template>
                        </el-table-column>
                        <el-table-column label="下单时间" align="center" prop="xdDate"/>
                        <el-table-column label="订单总额" align="center" prop="money"/>
                        <el-table-column label="备注" align="center" prop="remark"/>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-tooltip content="修改" placement="top">
                            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['demo:orderMain:edit']"></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['demo:orderMain:remove']"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
            />
        </el-card>
        <!-- 添加或修改订单主表对话框 -->
        <el-dialog :title="dialog.title" v-model="dialog.visible" width="1000px" append-to-body>
            <el-form ref="orderMainFormRef" :model="form" :rules="rules" label-width="80px">
                            <el-form-item label="订单编码" prop="orderCode">
                                <el-input v-model="form.orderCode" placeholder="请输入订单编码"/>
                            </el-form-item>
                            <el-form-item label="客户编号" prop="customerId">
                                <el-input
                                    :value="displayComputed[`displaycustomerId`]"
                                    placeholder="请选择客户编号"
                                    readonly
                                >
                                    <template #append>
                                        <el-button icon="Search" @click="popupVisible['customerId'] = true" />
                                    </template>
                                </el-input>
                            </el-form-item>
                            <el-form-item label="下单时间" prop="xdDate">
                                <el-date-picker clearable
                                                v-model="form.xdDate"
                                                type="date"
                                                value-format="YYYY-MM-DD"
                                                placeholder="请选择下单时间">
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="订单总额" prop="money">
                                <el-input v-model="form.money" placeholder="请输入订单总额"/>
                            </el-form-item>
                            <el-form-item label="备注" prop="remark">
                                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
                            </el-form-item>
                    <el-divider content-position="center">订单子表信息</el-divider>
                    <el-row :gutter="10" class="mb8">
                        <el-col :span="1.5">
                            <el-button type="primary" icon="Plus" @click="handleAddTestOrderGoods">添加</el-button>
                        </el-col>
                        <el-col :span="1.5">
                            <el-button type="danger" icon="Delete" @click="handleDeleteTestOrderGoods">删除</el-button>
                        </el-col>
                    </el-row>
                    <el-table :data="testOrderGoodsList" :row-class-name="rowTestOrderGoodsIndex"
                              @selection-change="handleTestOrderGoodsSelectionChange" ref="testOrderGoods">
                        <el-table-column type="selection" width="50" align="center"/>
                        <el-table-column label="序号" align="center" prop="index" width="50"/>
                                <el-table-column label="商品编码" prop="goodCode">
                                    <template #default="scope">
                                        <el-input
                                            v-model="scope.row.goodCode"
                                            placeholder="请选择商品编码"
                                            readonly
                                        >
                                            <template #append>
                                                <el-button
                                                    icon="Search"
                                                    @click="showSubPopupSelect('goodCode', scope.$index)"
                                                />
                                            </template>
                                        </el-input>
                                    </template>
                                </el-table-column>

                                <el-table-column label="商品名字" prop="goodName" width="150">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.goodName" placeholder="请输入商品名字"/>
                                    </template>
                                </el-table-column>
                                <el-table-column label="价格" prop="price" width="150">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.price" placeholder="请输入价格"/>
                                    </template>
                                </el-table-column>
                                <el-table-column label="数量" prop="num" width="150">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.num" placeholder="请输入数量"/>
                                    </template>
                                </el-table-column>
                                <el-table-column label="单品总价" prop="zongPrice" width="150">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.zongPrice" placeholder="请输入单品总价"/>
                                    </template>
                                </el-table-column>
                    </el-table>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 动态生成弹窗选择组件 -->
        <!-- 主表弹窗 -->
        <PopupSelect
            v-for="column in mainColumns.filter(c=>c.htmlType==='popup')"
            :key="'main_'+column.javaField"
            v-model:visible="popupVisible[column.javaField]"
            :dict-type="column.dictType"
            :dict-fields="getDictFields(column)"
            :mapping="getMainMapping(column)"
            :selected-values="getMainSelectedValues(column)"
            :title="`选择${column.columnComment}`"
            @select="(data) => handleMainSelect(data, column)"
        />
            <!-- 子表弹窗 -->
            <PopupSelect
                v-for="column in subColumns.filter(c=>c.htmlType==='popup')"
                :key="'sub_'+column.javaField"
                v-model:visible="subPopupVisible[column.javaField]"
                :dict-type="column.dictType"
                :dict-fields="getDictFields(column)"
                :mapping="getSubMapping(column)"
                :selected-values="getSubSelectedValues(column)"
                :title="`选择${column.columnComment}`"
                @select="(data) => handleSubSelect(data, column)"
            />
    </div>
</template>

<script setup name="OrderMain" lang="ts">
import { ref, watch, computed, triggerRef } from 'vue'
import { dayjs } from "element-plus";
import { listOrderMain, getOrderMain, delOrderMain, addOrderMain, updateOrderMain } from '@/api/demo/orderMain';
import { OrderMainVO, OrderMainQuery, OrderMainForm } from '@/api/demo/orderMain/types';
import { listTableData } from "@/api/online";
import { getTableColumns } from '@/api/tool/gen';

// PopupSelect组件引入
const PopupSelect = defineAsyncComponent(() => import('@/components/PopupSelect/index.vue'));
import { useDict } from '@/hooks/useDict';
import { useTable } from '@/hooks/useTable';
import { useTableForm } from '@/hooks/useTableForm';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const orderMainList = ref < OrderMainVO[] > ([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref < Array < string | number >> ([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref < ElFormInstance > ();
const orderMainFormRef = ref < ElFormInstance > ();

const dialog = reactive < DialogOption > ({
    visible: false,
    title: ''
});

const checkedTestOrderGoods = ref(0)
const testOrderGoodsList = ref<any>([])

const initFormData: OrderMainForm = {
              id: undefined ,
              orderCode: undefined ,
              customerId: undefined ,
              xdDate: undefined ,
              money: undefined ,
              remark: undefined ,
            testOrderGoodsList: []
}
    const data = reactive < PageData < OrderMainForm, OrderMainQuery>>({
        form: {...initFormData},
        queryParams: {
            pageNum: 1,
            pageSize: 10,
                    orderCode: undefined,
                    customerId: undefined,
                    xdDate: undefined,
                    money: undefined,
        params: {
    	}
    },
    rules: {
                    id: [
                    { required: true, message: "主键不能为空", trigger: "blur" }
                ],
                    orderCode: [
                    { required: true, message: "订单编码不能为空", trigger: "blur" }
                ],
                    customerId: [
                    { required: true, message: "客户编号不能为空", trigger: "blur" }
                ],
                    xdDate: [
                    { required: true, message: "下单时间不能为空", trigger: "blur" }
                ],
                    money: [
                    { required: true, message: "订单总额不能为空", trigger: "blur" }
                ],
    }
    });

    const {queryParams, form, rules} = toRefs(data);

    // 主表和子表列数据分开管理
    const mainColumns = ref<any[]>([]);
    const subColumns = ref<any[]>([]);
    // 弹窗可见状态分开管理
    const popupVisible = reactive<Record<string, boolean>>({}); // 主表
    const subPopupVisible = reactive<Record<string, boolean>>({}); // 子表
    const currentSubRowIndex = ref(-1); // 当前操作的子表行索引
    //修改时候显示名称用
    const relationDict = ref<Record<string, Record<string, string>>>({});

    /** 查询订单主表列表 */
    const getList = async () => {
        loading.value = true;
        const res = await listOrderMain(queryParams.value);
        orderMainList.value = res.rows;
        total.value = res.total;
        loading.value = false;
    }

    /** 取消按钮 */
    const cancel = () => {
        reset();
        dialog.visible = false;
    }

    /** 表单重置 */
    const reset = () => {
        form.value = {...initFormData};
        orderMainFormRef.value?.resetFields();
        testOrderGoodsList.value = []
    }

    /** 搜索按钮操作 */
    const handleQuery = () => {
        queryParams.value.pageNum = 1;
        getList();
    }

    /** 重置按钮操作 */
    const resetQuery = () => {
        queryFormRef.value?.resetFields();
        handleQuery();
    }

    /** 多选框选中数据 */
    const handleSelectionChange = (selection: OrderMainVO[]) => {
        ids.value = selection.map(item => item.id);
        single.value = selection.length != 1;
        multiple.value = !selection.length;
    }

    // 动态获取字段配置
    const getDictFields = (column: any) => {
        try {
            return JSON.parse(column.dictFields || '{}');
        } catch {
            return { id: 'ID', name: '名称' };
        }
    };

    // 改进的getMainMapping方法（支持复杂映射）
    const getMainMapping = (column: any) => {
        try {
            const defaultMapping = { id: column.javaField, name: `${column.javaField}Name` };
                const customMapping = JSON.parse(column.mapping || '{}');

                // 合并默认映射和自定义映射
                return { ...defaultMapping, ...customMapping };
            } catch {
                return { id: column.javaField, name: `${column.javaField}Name` };
            }
        };

    // 主表选择处理
    const handleMainSelect = (data: any, column: any) => {
        const mapping = getMainMapping(column);
        // 同时更新ID和Name字段
        form.value[column.javaField] = data.id;
        form.value[`${column.javaField}Name`] = data.name;

        // 更新主表字段
        Object.entries(mapping).forEach(([source, target]) => {
            if (data[target] !== undefined) {
                form.value[target] = data[target];
            }
        });
        triggerRef(form); // 强制触发响应式更新
        popupVisible[column.javaField] = false;
    };



    // 自动生成编号逻辑（增强版）
    const generateBusinessNo = (column: any) => {
        try {
            const ruleConfig = JSON.parse(column.onChange || '{}').onCodeGenerate;
            if (!ruleConfig?.autoGenerateRule) return;

            let result = ruleConfig.autoGenerateRule;
            const params = ruleConfig.generateParams || {};

            // 替换时间戳
            if (result.includes('{timestamp}')) {
                const timestamp = params.format
                    ? dayjs().format(params.format)
                    : Date.now().toString();
                result = result.replace(/{timestamp}/g, timestamp);
            }

            // 替换序列号
            if (result.includes('{sequence}')) {
                const sequence = generateSequence(column.javaField);
                result = result.replace(/{sequence}/g, sequence);
            }

            return result;
        } catch (e) {
            console.error('编号生成失败:', e);
        }
    };

    //获取表popup字段的字典信息
    const getDictTypeData = async (table: string) => {
        const res = await listTableData(table, queryParams.value);

        // 为当前列创建独立存储空间
        relationDict.value[table] = res.rows.reduce((dict, item) => {
            dict[item.id] = item.name;
            return dict;
        }, {} as Record<string, string>);
    }


    // 获取列配置
    const getColumns = async () => {
        const main = await getTableColumns("test_order_main"); // 主表名
        mainColumns.value = main;
        const sub = await getTableColumns("test_order_goods"); // 子表名
        subColumns.value = sub;

        // 加载所有popup字段的字典数据
        mainColumns.value
            .filter(col => col.htmlType === 'popup' && col.dictType)
            .forEach(col => getDictTypeData(col.dictType));
    };

    /** 新增按钮操作 */
    const handleAdd = () => {
        reset();
        mainColumns.value.forEach(column => {
            if (column.insert && column.htmlType === 'input') {
                form.value[column.javaField] = generateBusinessNo(column);
            }
        });
        dialog.visible = true;
        dialog.title = "添加订单主表";
    }

    // 生成动态display计算属性（主表）
    const displayComputed = computed(() => {
        return mainColumns.value
            .filter(col => col.htmlType === 'popup')
            .reduce((acc, col) => {
                const displayKey = `display${col.javaField}`;
                // 获取显示值
                acc[displayKey] = col.dictType
                    ? relationDict.value[col.dictType][form.value[col.javaField]]
                    : form.value[`${col.javaField}Name`];
                return acc;
            }, {} as Record<string, string>);
        });

    // 修改handleUpdate方法
    const handleUpdate = async (row? : OrderMainVO) => {
        reset();
        const _id = row?.id || ids.value[0]
        const res = await getOrderMain(_id);

        // 深拷贝数据
        const formData = JSON.parse(JSON.stringify(res.data));

        // 处理主表popup字段的显示值
        mainColumns.value.forEach(col => {
            if (col.htmlType === 'popup') {
                const mapping = getMainMapping(col);
                Object.values(mapping).forEach(target => {
                    if (formData[target] === undefined) {
                        formData[target] = res.data[col.javaField];
                    }
                });
            }
        });

        Object.assign(form.value, formData);
        testOrderGoodsList.value = res.data.testOrderGoodsList.map(item => ({...item}));
        dialog.visible = true;
        dialog.title = "修改订单主表";
    };

    /** 提交按钮 */
    const submitForm = () => {
            orderMainFormRef.value?.validate(async (valid: boolean) => {
            if (valid) {
                buttonLoading.value = true;
                    form.value.testOrderGoodsList = testOrderGoodsList.value;

                if (form.value.id) {
                    await updateOrderMain(form.value).finally(() => buttonLoading.value = false);
                } else {
                    await addOrderMain(form.value).finally(() => buttonLoading.value = false);
                }
                proxy?.$modal.msgSuccess("修改成功");
                dialog.visible = false;
                await getList();
            }
        });
    }

    /** 删除按钮操作 */
    const handleDelete = async (row? : OrderMainVO) => {
        const _ids = row?.id||ids.value;
        await proxy?.$modal.confirm('是否确认删除订单主表编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
        await delOrderMain(_ids);
        proxy?.$modal.msgSuccess("删除成功");
        await getList();
    }


    // 子表映射处理
    const getSubMapping = (column: any) => {
        try {
            return JSON.parse(column.mapping || '{}');
        } catch {
            return {};
        }
    };
    // 子表选择处理
    const handleSubSelect = (data: any, column: any) => {
        if (currentSubRowIndex.value === -1) return;

        const mapping = getSubMapping(column);
        const row = testOrderGoodsList.value[currentSubRowIndex.value];

        // 更新子表字段
        // 更新所有映射字段
        Object.entries(mapping).forEach(([sourceKey, targetKey]) => {
            if (data[targetKey] !== undefined) {
                row[targetKey] = data[targetKey];
            }
        });
        // 自动计算单品总价
        row.num = 1;
        row.zongPrice = (parseFloat(row.price) * parseInt(row.num)).toFixed(2);
        //同时给主表的总价赋值
        form.value.money = testOrderGoodsList.value.reduce((total, item) => total + parseFloat(item.zongPrice), 0).toFixed(2);
        // 触发视图更新
        testOrderGoodsList.value = [...testOrderGoodsList.value];
        subPopupVisible[column.javaField] = false;
    };

    // 添加监听自动计算总价
    watch(() => testOrderGoodsList.value, (newVal) => {
        newVal.forEach(item => {
            if (item.price && item.num) {
                item.zongPrice = (parseFloat(item.price) * parseInt(item.num)).toFixed(2);
            }
        });
        // 触发总额更新
        form.value.money = newVal.reduce((sum, item) => sum + (parseFloat(item.zongPrice) || 0), 0).toFixed(2)
    }, { deep: true });

    // 显示子表弹窗
    const showSubPopupSelect = (field: string, index: number) => {
        currentSubRowIndex.value = index;
        subPopupVisible[field] = true;
    };

    // 主表值获取
    const getMainSelectedValues = (column: any) => {
        return [form.value[column.javaField]];
    };


    // 子表值获取
    const getSubSelectedValues = (column: any) => {
        if (currentSubRowIndex.value === -1) return [];
        const row = testOrderGoodsList.value[currentSubRowIndex.value];
        // 检查 row 和 column.javaField 是否存在
        if (!row || !column?.javaField) return [];
        return [row[column.javaField]];
    };

    /** 订单子表序号 */
    function rowTestOrderGoodsIndex({row, rowIndex})
    {
        row.index = rowIndex + 1;
    }

    /** 订单子表添加按钮操作 */
    function handleAddTestOrderGoods() {
        let obj = {};
        obj.goodCode = "";
        obj.goodName = "";
        obj.price = "";
        obj.num = "";
        obj.zongPrice = "";
        testOrderGoodsList.value.push(obj);
    }

    /** 订单子表删除按钮操作 */
    function handleDeleteTestOrderGoods(){
        if (checkedTestOrderGoods.value.length == 0) {
            proxy.$modal.msgError("请先选择要删除的订单子表数据");
	}
    else
        {
            const testOrderGoodss = testOrderGoodsList.value;
            const checkedTestOrderGoodss = checkedTestOrderGoods.value;
            testOrderGoodsList.value = testOrderGoodss.filter(function (item) {
                return checkedTestOrderGoodss.indexOf(item.index) == -1
            });
        }
    }

    /** 复选框选中数据 */
    function handleTestOrderGoodsSelectionChange(selection)
    {
        checkedTestOrderGoods.value = selection.map(item => item.index)
    }


    /** 导出按钮操作 */
    const handleExport = () => {
        proxy?.download('demo/orderMain/export', {
            ...queryParams.value
        }, `orderMain_${new Date().getTime()}.xlsx`)
    }

    onMounted(() => {
        getColumns();
        getList();
    });
</script>
